<template>
    <div class="app-container">
      <div class="filter-container">
        <el-input v-model="listQuery.productName" placeholder="商品名称" style="width: 150px; margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.userName" placeholder="收货人姓名" style="width: 150px; margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.userPhone" placeholder="收货人电话" style="width: 150px; margin-right: 10px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          {{ $t('table.export') }}
        </el-button>
      </div>
  
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%; "
        @sort-change="sortChange"
      >
        <!-- 渲染表单 -->
        <el-table-column :label="$t('table.id')" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.orderId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="寄件人" width="80px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.userName }}</span>
            </template>
        </el-table-column>
        <el-table-column label="寄件人电话" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.userPhone }}</span>
            </template>
        </el-table-column>
        <el-table-column label="商品名" width="120px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.productName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="60px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.unitPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="60px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.quantity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品总价" width="90px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" width="100px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.orderTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发货时间" width="120px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.shipTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收件人" width="90px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.recipientName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收件人电话" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.recipientPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120px" align="center">
          <template slot-scope="{row}">
            <el-select v-model="row.orderStatus" placeholder="请选择状态">
            <el-option
              v-for="status in statuses"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" width="120px" align="center">
          <template slot-scope="{row}">
            <el-select v-model="row.paymentMethod" placeholder="请选支付方式">
                <el-option
                v-for="pay in pays"
                    :key="pay.value"
                    :label="pay.label"
                    :value="pay.value">
                </el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- 表单内部按钮 -->
        <el-table-column :label="$t('table.actions')" align="center" width="150" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button v-if="row.status!='edit'" size="mini" type="primary" @click="handleUpdate(row,$index)">
            {{ $t('table.edit') }}
          </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  

      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { findByPage,updateOreder } from '@/api/order'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  
  export default {
  
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
  
    },
    data() {
      return {
        tableKey: 0,
        list: null, // 表格集合数据
        total: 0, // 总条数
        listLoading: true, // 是否被加载 true未被加载
        listQuery: { // 查询的筛选条件
          page: 1, // 页数
          limit: 10, // 每页条数
          productName: undefined,
          userPhone: undefined,
          userN3ame: undefined
        },
        statuses: [
        { value: '待发货', label: '待发货' },
        { value: '已发货', label: '已发货' },
        { value: '已收货', label: '已收货' },
        ],
        pays: [
            { value: '支付宝', label: '支付宝' },
            { value: '微信支付', label: '微信支付' },
            { value: '银联', label: '银联' },
        ],
        dialogPvVisible: false,
        pvData: [],
        rules: {
          userName: [{ required: true, message: 'type is required', trigger: 'change' }],
          tiuserPhone: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
  
      getList() { // 获取 list  total
        // 设置未加载
        this.listLoading = true
        // Axios请求后端
        findByPage(this.listQuery).then(response => {
          // console.log(response.data.list)
          // console.log(response.data.list[1].userName)
          this.list = response.data.list
          // console.log(this.list)
          this.total = response.data.total
  
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 10)
        })
      },
  
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
  
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },


      // 点击表单内部按钮是 修改的触发事件
      handleUpdate(row) {
        console.log(11111)
        let data = {
           orderId: row.orderId,
           orderStatus:row.orderStatus,
           paymentMethod:row.paymentMethod
        }
        updateOreder(data).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      })
      },
       handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      // formatDate() {
      //   // 确保 birthDate 是一个 Date 对象
      //   if (typeof this.temp.birthDate === 'string') {
      //     this.temp.birthDate = new Date(this.temp.birthDate) // 转换为 Date 对象
      //   }
  
      //   // 确保 birthDate 是有效的 Date 对象
      //   if (this.temp.birthDate instanceof Date && !isNaN(this.temp.birthDate)) {
      //     this.temp.birthDate = this.temp.birthDate.toISOString().split('T')[0] // 转换为 yyyy-MM-dd 格式
      //   } else {
      //     console.error('Invalid date format') // 处理无效日期的情况
      //   }
      // },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
  </script>
  
  